import RSATool from '../../lib/RSATool';
import configTool from '../../com/configTool';

function TokenAuthorityHandler() {
    return async (ctx: any, next: Function) => {
        const token_get = ctx.request.query?.token;
        const token_body = ctx.request.body?.token;
        const token_header = ctx.request.header?.token;
        const token = token_get || token_body || token_header;

        if (decodeURI(ctx.request.url).includes('/AuthorizeServer/login')) {
            await next();
        } else if (decodeURI(ctx.request.url) === '/') {
            await next();

            ctx.status = 200;
            ctx.body = {code: 200, message: '服务已启动成功...版本号：'+configTool.baseConfig.version, desc: new Date().toISOString()};
        } else if (token) {
            try {
                let plaintext = RSATool.decrypt(token, configTool.baseConfig.privateDer);
                let userObj = JSON.parse(plaintext);
                if (new Date(userObj.token_expired_date).getTime() < (new Date()).getTime()) {
                    ctx.status = 401;
                    ctx.body = {code: 401, message: 'Token 已过期，请重新登录', desc: `Token 已过期，请重新登录`};
                } else if (userObj.ip !== ctx.request.ip) {
                    ctx.body = {code: 401, message: '未授权的IP地址用户', desc: `请重新登录`};
                } else {
                    await next();
                }
            } catch (e) {
                ctx.status = 401;
                ctx.response.body = {code: 401, message: 'Token 错误', desc: `Token 错误`};
            }
        } else {
            ctx.response.status = 401;
            ctx.response.body = {
                code: 401, message: '参数缺少 Token', desc: `参数缺少 Token`
            };
        }
    };
}


export default TokenAuthorityHandler;
